/*
 * v1.2 by tonydon
 */
package cn.txdnet.key;

import java.util.Calendar;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import txdnet.util.Logger;

/**
 * @author txdnet
 */
public final class AtomicGen {

    private static Lock lock = new ReentrantLock();
    private static int n = 0;
//    private static int minSeg = AtomicGen.getMinSeg();
    private static int hourSeg = AtomicGen.getHourSeg();
    private final static int m = 999999999;

//    private static int getMinSeg(Calendar cd) {
//        int totMinute = cd.get(Calendar.HOUR_OF_DAY) * 60 + cd.get(Calendar.MINUTE);
//        return (totMinute + 1);
//    }
//
//    private static int getMinSeg() {
//        return AtomicGen.getMinSeg(Calendar.getInstance());
//    }
    
    private static int getHourSeg(Calendar cd){
        return  cd.get(Calendar.HOUR_OF_DAY);
    }
    
    private static int getHourSeg(){
        return AtomicGen.getHourSeg(Calendar.getInstance());
    }

    private static int getYearSeg(Calendar cd) {
        int y = cd.get(Calendar.YEAR) - 2011;
        return y;
    }

    /*
     * 利用计数器和时间允许范围生成ID，适合订单ID，高并发ID生成环境
     * @return String
     */
    public static String getId() {
        String id = null;
        int day, yseg, seg0;
        Calendar cd;
        lock.lock();
        cd = Calendar.getInstance();
        day = cd.get(Calendar.DAY_OF_YEAR);
        yseg = getYearSeg(cd);
        seg0 = getHourSeg(cd);
        try {
            if (seg0 == hourSeg) {
                if (n < m) { // 如果在可控值范围 m 内
                    n++;
                    id = String.format("%d%03d%02d%09d", yseg, day, seg0, n);
                }
            } else {
                hourSeg = seg0; // 已越过记录值，新记录点开始
                n = 1;
                id = String.format("%d%03d%02d%09d", yseg, day, seg0, n);
            }
        } catch (Exception e) {
            Logger.error(AtomicGen.class, e.toString());
        } finally {
            lock.unlock();
        }
        return id;
    }
  
//    public static void main(String... args) throws Exception{
//        for(int n=1; n<100; n++){
//            new Thread(new ThreadDemo()).start();
//        }
//    }
}

//class ThreadDemo implements Runnable{
//
//    @Override
//    public void run() {
//        System.out.println(Thread.currentThread().getId()+": sid= "+ GenId.makeRndChr(2, Def.MAP2)+"-" + GenId.makeSid() +"-"+GenId.makeRndChr(6, Def.MAP2));
//        System.out.println(Thread.currentThread().getId()+": id= " + AtomicGen.getId());
//    }
//}